import {
    caseFromRegister,
    getLoginDoctor,
    getRegistersDoctorHave,
    uploadCase,
} from "../utils/common_network.js";
import popupInfo from "../../components/popupInfo.js";
import {exist} from "../../utils.js";
import {ResultCode} from "../../network.js";
import squareButton from "../../components/squareButton.js";
import popupSearch from "../../components/popupSearch.js";
import {searchValueChangeDoing} from "../utils/popupSearchUtils.js";

export default {
    components: {
        'popup-info': popupInfo,
        'square-button': squareButton,
        'popup-search': popupSearch,
    },
    setup() {
        const popup = Vue.ref(null);
        const popupSearch = Vue.ref(null);
        const router = VueRouter.useRouter();
        const doctor = Vue.ref({name: "医生姓名"});
        const registerList = Vue.ref([]);
        const selectRIndex = Vue.ref(-1);

        function backToIndex() {
            router.push({path: '/'});
        }

        Vue.onMounted(async () => {
            getLoginDoctor(popup, backToIndex, doctor);
            await getRegistersDoctorHave(registerList);
            contentResize();
        });

        const caseOuter = Vue.ref(null);
        const caseTitle = Vue.ref(null);
        const caseContent = Vue.ref(null);
        const caseFooter = Vue.ref(null);

        function contentResize() {
            if (exist(caseOuter.value) && exist(caseTitle.value) && exist(caseContent.value)
                && exist(caseFooter.value)) {
                // console.log('resize');
                const h1 = caseTitle.value.clientHeight;
                const h2 = caseFooter.value.clientHeight;
                const h = caseOuter.value.clientHeight;
                // console.log(h1, h2, h);
                caseContent.value.style.height = (h - h1 - h2 - 1) + "px";
            }
        }

        window.addEventListener('resize', contentResize);

        Vue.onBeforeUnmount(() => {
            window.removeEventListener('resize', contentResize);
        });

        const selectCaseInfo = Vue.ref({
            userName: "",
            // gender:
        })

        async function getCaseInfo(rId) {
            await caseFromRegister(rId, selectCaseInfo)
                .then(r => {
                    const responseResult = r.data;
                    if (responseResult.code === ResultCode.PERMISSION_DENIED) {
                        popup.value.show("您没有权限！");
                    }
                }).catch(_ => popup.value.show("网络连接异常！"));
        }

        async function onRClick(index) {
            if (selectRIndex.value !== index) {
                selectRIndex.value = index;
                const rId = registerList.value[selectRIndex.value].id;
                await getCaseInfo(rId);
                // console.log(selectCaseInfo.value);
                axios.post("/case/get_inspections", {value: selectCaseInfo.value.id})
                    .then(r => {
                        const responseResult = r.data;
                        if (responseResult.code === ResultCode.SUCCESS) {
                            choseIns.value.clear();
                            for (const ins of responseResult.data) {
                                let i = handleItem(ins);
                                choseIns.value.set(i.id, i);
                            }
                        }
                        console.log(r);
                    }).catch(_ => popup.value.show("网络连接异常！"));
                axios.post("/case/get_medicines", {value: selectCaseInfo.value.id})
                    .then(r => {
                        const responseResult = r.data;
                        if (responseResult.code === ResultCode.SUCCESS) {
                            choseMedicine.value.clear();
                            for (const ins of responseResult.data) {
                                let i = handleItem(ins);
                                choseMedicine.value.set(i.id, i);
                            }
                        }
                        console.log(r);
                    }).catch(_ => popup.value.show("网络连接异常！"));

            }
        }

        const selectRItem = Vue.computed({
            get() {
                const r = registerList.value[selectRIndex.value];
                if (exist(r)) {
                    return r;
                }
                return {};
            }
        });

        function getRStyle(index) {
            if (index === selectRIndex.value) {
                return {
                    'font-weight': 'bold',
                    'font-size': '24px',
                }
            }
            return {
                'font-size': '20px',
            }
        }

        function genderFromBool(g) {
            // console.log(g);
            if (exist(g)) {
                if (g) {
                    return "男";
                }
                return "女";
            }
        }

        function getComeTime() {
            const r = registerList.value[selectRIndex.value];
            if (exist(r)) {
                const comeTime = r['comeTime'];
                // console.log(comeTime);
                // console.log(r['gender']);
                if (exist(comeTime)) {
                    return comeTime;
                }
                return "尚未就诊";
            }

        }

        function getCaseState() {
            if (selectRIndex.value === -1) {
                return;
            }
            if (exist(selectCaseInfo.value)) {
                return "已创建";
            }
            return "未创建";
        }

        const showCreateCaseBtn = Vue.computed({
            get() {
                return !(selectRIndex.value === -1 || exist(selectCaseInfo.value));
            }
        });

        function createCase() {
            return {
                "doctorId": doctor.value.id,
                "doctorOrder": "",
                "patientStatement": "",
                "userId": registerList.value[selectRIndex.value]['userId'],
                "registerId": registerList.value[selectRIndex.value]['id'],
            }
        }

        async function myUploadCase(c, callBackInfo) {
            const r = registerList.value[selectRIndex.value];
            if (!exist(r)) {
                popup.value.show("您尚未选中任何患者");
                return;
            }
            const rId = r.id;
            let success = true;
            let mdcCounts = [];
            for (let v of choseMedicine.value.values()) {
                mdcCounts.push(v.count);
            }
            await uploadCase(c, choseIns.value.keys(), choseMedicine.value.keys(), mdcCounts)
                .then(response => {
                    const responseResult = response.data;
                    if (responseResult.code !== ResultCode.SUCCESS) {
                        // console.log()
                        success = false;
                    }
                }).catch(_ => success = false);
            if (!success) {
                popup.value.show("创建失败，请重试");
            } else {
                popup.value.show(callBackInfo);
            }
            getCaseInfo(rId).then().catch(_ => popup.value.show("网络连接异常！"));
        }

        function onCreateCaseClick() {
            const c = createCase();
            console.log(c);
            popup.value.onConfirm = () => {
                myUploadCase(c, "创建成功").then();
            };
            popup.value.show("请确认患者已经前来就诊，点击确认继续");
        }

        const caseContentIndex = Vue.ref(0);

        const textAreaValue = Vue.computed({
            get() {
                if (!exist(selectCaseInfo.value)) {
                    return "";
                }
                switch (caseContentIndex.value) {
                    case 0:
                        return selectCaseInfo.value['patientStatement'];
                    case 1:
                        return selectCaseInfo.value['doctorOrder'];
                }
            },
            set(v) {
                if (!exist(selectCaseInfo.value)) {
                    return;
                }
                switch (caseContentIndex.value) {
                    case 0:
                        selectCaseInfo.value['patientStatement'] = v;
                        break
                    case 1:
                        selectCaseInfo.value['doctorOrder'] = v;
                }
            }
        })

        function getCaseContentStyle(index) {
            const r = {
                'background-color': 'rgb(226, 246, 248)'
            }
            if (index === caseContentIndex.value) {
                if (index === 0) {
                    r['border-top-left-radius'] = '15px';
                } else if (index === 3) {
                    r['border-top-right-radius'] = '15px';
                }
                return r;
            }
        }

        function onSubmitCase() {
            popup.value.onConfirm = () => {
                myUploadCase(selectCaseInfo.value, "提交成功").then();
            };
            popup.value.show("确认要提交病历信息吗？新提交的病历信息会覆盖原有的信息");
        }

        const choseMedicine = Vue.ref(new Map());
        const choseIns = Vue.ref(new Map());
        const choseList = Vue.computed({
            get() {
                if (caseContentIndex.value === 2) {
                    return choseIns.value;
                } else if (caseContentIndex.value === 3) {
                    return choseMedicine.value;
                }
                return {
                    values() {
                        return [];
                    }
                }
            },
        });

        function onDeleteClick(itemId) {
            if (caseContentIndex.value === 2) {
                choseIns.value.delete(itemId);
            } else if (caseContentIndex.value === 3) {
                let i = choseMedicine.value.get(itemId);
                i.count--;
                if (i.count <= 0) {
                    choseMedicine.value.delete(itemId);
                } else {
                    choseMedicine.value.set(itemId, i);
                }
            }
        }

        function handleItem(i) {
            let count = i['count'];
            if (!exist(count)) {
                count = 0;
            }
            return {
                id: i['id'],
                name: i['name'],
                price: i['price'],
                count: count
            };
        }

        function onAddClick() {
            let nowList, itemName;
            if (caseContentIndex.value === 2) {
                nowList = insList.value;
                itemName = "检查项目";
            } else if (caseContentIndex.value === 3) {
                nowList = medicineList.value;
                itemName = "药品";
            }
            if (!exist(nowList) || nowList.length <= 0) {
                popup.value.show("您没有选中任何" + itemName);
                return;
            }
            const nowIndex = selectSearchIndex.value;
            const item = handleItem(nowList[nowIndex]);
            console.log(item);
            if (caseContentIndex.value === 2) {
                if (choseIns.value.has(item.id)) {
                    popup.value.show("您已经添加过这个检查项目了");
                    return;
                }
                choseIns.value.set(item.id, item);
            } else if (caseContentIndex.value === 3) {
                let i = choseMedicine.value.get(item.id);
                if (!exist(i)) {
                    i = item;
                }
                i.count++;
                choseMedicine.value.set(item.id, i);
            }
        }

        function onCaseInfoClick() {
            const r = registerList.value[selectRIndex.value];
            if (!exist(r)) {
                popup.value.show("您尚未选中任何患者");
                return;
            }
            router.push('/case_info/' + r.userId);
        }

        const insList = Vue.ref([]);
        const medicineList = Vue.ref([]);
        const searchList = Vue.computed({
            get() {
                if (caseContentIndex.value === 2) {
                    return insList.value;
                } else if (caseContentIndex.value === 3) {
                    return medicineList.value;
                }
            }
        })

        function onTextChange() {
            const newValue = searchText.value;
            console.log(newValue);
            let url;
            if (caseContentIndex.value === 2) {
                url = "/inspection/search_type";
            } else if (caseContentIndex.value === 3) {
                url = "/medicine/search";
            }
            axios.post(url, {value: newValue})
                .then(r => {
                    const responseResult = r.data;
                    if (responseResult.code === ResultCode.SUCCESS) {
                        if (caseContentIndex.value === 2) {
                            insList.value = responseResult.data;
                        } else if (caseContentIndex.value === 3) {
                            medicineList.value = responseResult.data;
                        }
                    }
                    console.log(r);
                });
        }

        function contentIndexChange(index) {
            if (caseContentIndex.value === index) {
                return;
            }
            const r = registerList.value[selectRIndex.value];
            if (!exist(r)) {
                popup.value.show("您尚未选中任何患者");
                return;
            }
            caseContentIndex.value = index;
            if (index === 2 || index === 3) {
                onTextChange();
            }
            selectSearchIndex.value = 0;
        }

        const searchText = Vue.ref("");
        const selectSearchIndex = Vue.ref(0);

        function onSearchItemClick(index) {
            selectSearchIndex.value = index;
        }

        function getSearchStyle(index) {
            if (index === selectSearchIndex.value) {
                return {
                    'background-color': 'rgb(253, 231, 176)',
                }
            }
        }

        function onBackToIndexClick() {
            router.push({path: '/'});
        }

        function showMdcs() {
            console.log("showMdcs");
            popupSearch.value.widthInParent = 80;
            popupSearch.value.heightInParent = 80;
            popupSearch.value.onTextChange = (v) => {
                searchValueChangeDoing(v, "/medicine/search", popupSearch,
                    (resultList) => {
                        return (i) => {
                            popupSearch.value.hide();
                            const item = resultList[i];
                            // console.log(popup.value.onConfirm);
                            popup.value.onConfirm = showMdcs;
                            popup.value.onCancel = showMdcs;
                            popup.value.show(`id:${item.id}，单价:${item.price}`, item.name);
                        };
                    });
            };
            popupSearch.value.show("药品信息");
        }

        function toAnswer() {
            router.push('/topic_info/1');
        }

        return {
            popup, doctor, registerList, onRClick,
            getRStyle, caseTitle,
            caseContent, caseFooter, caseOuter,
            selectRItem, genderFromBool, getComeTime,
            getCaseState, showCreateCaseBtn, onCreateCaseClick,
            textAreaValue, caseContentIndex,
            getCaseContentStyle, onSubmitCase, onAddClick,
            onCaseInfoClick, searchList, onTextChange, contentIndexChange,
            searchText, onSearchItemClick, getSearchStyle, choseList,
            onDeleteClick, onBackToIndexClick, showMdcs, toAnswer, popupSearch
        }
    },
    template: `<div class="container-fluid nss-font" style="height: 100%;">
    <popup-info ref="popup"></popup-info>
    <popup-search ref="popupSearch">
    </popup-search>
    <square-button background-url="/images/logo.png"
                   :width-in-parent=12
                   right="5%"
                   top="1%"
                   :z-index="1031"
                   @onClick="onBackToIndexClick"
    ></square-button>
    <div class="row" style="height: 100%;">
        <div style="height: 100%; background: linear-gradient(rgba(184,223,238,1) 33.02%,rgba(219,243,251,0) 100%); padding-left: 0; padding-right: 0;"
             class="col-md-2">
            <div style="width: 100%; border-bottom: 1px solid; height: 25%;">
                <div style="height: 67%;"></div>
                <div style="height: 33%; text-align: center; font-size: 24px;">
                    医生：{{doctor.name}}
                </div>
            </div>
            <div style="height: 60px; font-size: 24px; text-align: center; line-height: 60px; 
            border-bottom: 1px solid;font-weight: bold;">
                患者信息管理
            </div>
            <div style="height: 60px; font-size: 24px; text-align: center; line-height: 60px;
             border-bottom: 1px solid;cursor: pointer;" @click="showMdcs">
                药品信息查询
            </div>
            <div style="height: 60px; font-size: 24px; text-align: center;
             line-height: 60px; border-bottom: 1px solid;cursor: pointer;" @click="toAnswer">
                咨询解答
            </div>
<!--            <div style="height: 60px; font-size: 24px; text-align: center; line-height: 60px; border-bottom: 1px solid;">-->
<!--                其他医院转诊-->
<!--            </div>-->
        </div>
        <div class="col-md-10" style="padding-left: 0; padding-right: 5px; height: 100%;padding-bottom: 5px;">
            <div style="height: 25%;">
                <div class="row"
                     style="margin-left: 0; margin-right: 0; height: 100%; padding-top: 20px; padding-bottom: 20px;">
                    <div class="col-md-5" style="height: 100%; padding-top: 10px; padding-bottom: 10px;">
                        <div style="width: 100%; height: 100%; border: 1px solid;font-size: 18px;">
                            <div class="row" style="height: 33%; margin-left: 0; margin-right: 0;">
                                <div class="col-md-4" style="padding-top: 5px;">
                                    姓名：{{selectRItem['userName']}}
                                </div>
                                <div class="col-md-4" style="padding-top: 5px;">
                                    性别：{{genderFromBool(selectRItem['userGender'])}}
                                </div>
                                <div class="col-md-4">
                                </div>
                            </div>
                            <div class="row" style="height: 33%; margin-left: 0; margin-right: 0;">
                                <div class="col-md-4" style="padding-top: 5px;">
                                    类型：门诊
                                </div>
                                <div class="col-md-8" style="padding-top: 5px;">
                                    就诊时间：{{getComeTime()}}
                                </div>
                            </div>
                            <div class="row" style="height: 33%; margin-left: 0; margin-right: 0;">
                                <div class="col-md-12" style="padding-top: 5px;">
                                    家庭地址：{{selectRItem['userAddress']}}
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4" style="height: 100%; padding-top: 10px; padding-bottom: 10px;">
                        <div style="width: 100%; height: 100%; border: 1px solid;font-size: 18px;">
                            <div class="row" style="margin-left: 0; margin-right: 0; height: 33%;">
                                <div class="col-md-12" style="padding-top: 5px;">
                                    就诊号：{{selectRItem['id']}}
                                </div>
                            </div>
                            <div class="row" style="margin-left: 0; margin-right: 0; height: 34%;">
                                <div style="padding-top: 5px;" class="col-md-12">
                                    开方科室：{{selectRItem['departmentName']}}
                                </div>
                            </div>
                            <div class="row" style="margin-left: 0; margin-right: 0; height: 33%;">
                                <div style="padding-top: 5px;" class="col-md-12">
                                    病历状态：{{getCaseState()}}
                                    <div style="display: inline-block;font-size: 14px;
                                        border: 1px solid;border-radius: 10px;
                                        padding: 3px; cursor: pointer;" 
                                        v-show="showCreateCaseBtn"
                                        @click="onCreateCaseClick()">
                                        点击创建
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3" style="height: 100%; border-left: 1px solid;">
                    </div>
                </div>
            </div>
            <div style="height: 75%;">
                <div class="row" style="margin-left: 0; margin-right: 0; height: 100%;">
                    <div class="col-md-2"
                         style="text-align: center; height: 100%; border: 1px solid;
                         padding-left: 5px; padding-right: 5px;">
                        <div style="height: 100%; font-size: 20px;">
                            <div style="padding-top: 5px; padding-bottom: 5px; border-bottom: 2px solid;">
                                患者列表
                            </div>
                            <div v-for="(item, index) in registerList"
                                @click="onRClick(index)"
                                :style="getRStyle(index)"
                                style="padding-top: 5px; padding-bottom: 5px; border-bottom: 1px solid;
                                    cursor: pointer;">
                                {{item.userName}}
                            </div>
                        </div>
                    </div>
                    <div class="col-md-10 my-font" style="padding-top: 10px; padding-bottom: 10px;
                        border-right: 1px solid;border-top: 1px solid;border-bottom: 1px solid;
                        height: 100%;">
                        <div style="height: 100%; width: 100%; border: 1px solid; 
                        border-top-left-radius: 15px; border-top-right-radius: 15px;"
                        ref="caseOuter">
                            <div class="row" style="width: 100%; height: 40px; margin-left: 0;
                             margin-right: 0;" ref="caseTitle">
                                <div style="text-align: center; line-height: 40px; font-size: 20px;
                                    margin-left: 0; margin-right: 0; border-bottom: 1px solid;
                                    cursor: pointer;"
                                    class="col-md-3" @click="contentIndexChange(0)"
                                    :style="getCaseContentStyle(0)">
                                    患者陈述
                                </div>
                                <div style="text-align: center; line-height: 40px; font-size: 20px;
                                    margin-left: 0; margin-right: 0; border-bottom: 1px solid; 
                                    border-left: 1px solid;cursor: pointer;"
                                    class="col-md-3" @click="contentIndexChange(1)"
                                    :style="getCaseContentStyle(1)">
                                    医嘱
                                </div>
                                <div style="text-align: center; line-height: 40px; font-size: 20px;
                                    margin-left: 0; margin-right: 0; border-bottom: 1px solid;
                                    border-left: 1px solid;cursor: pointer;"
                                    class="col-md-3" @click="contentIndexChange(2)"
                                    :style="getCaseContentStyle(2)">
                                    检查
                                </div>
                                <div style="text-align: center; line-height: 40px; font-size: 20px;
                                    margin-left: 0; margin-right: 0; border-bottom: 1px solid;
                                    border-left: 1px solid;cursor: pointer;"
                                    class="col-md-3" @click="contentIndexChange(3)"
                                    :style="getCaseContentStyle(3)">
                                    药品
                                </div>
                            </div>
                            <div style="width: 100%;overflow-y: auto;"
                                ref="caseContent">
                                <textarea style="width: 100%;resize: none;font-size: 18px;
                                    height: 99%;" v-show="caseContentIndex===0||caseContentIndex===1"
                                    v-model="textAreaValue">
                                </textarea>
                                <div style="padding: 10px 0;min-height: 80%;"
                                    v-show="caseContentIndex===2||caseContentIndex===3">
                                    <div style="padding-bottom: 10px;">
                                        <input style="width: 40%;font-size: 20px;
                                        margin-left: 30%;margin-right: 30%;"
                                            type="text" @input="onTextChange" @click="onTextChange"
                                            v-model="searchText"/>
                                    </div>
                                    <div style="margin: 0;width: 100%;border-top: 1px solid;"
                                        class="row">
                                        <div style="height: 100%;padding: 0;font-size: 20px;
                                            border-right: 1px solid;"
                                            class="col-md-6">
                                            <div style="padding-left: 25px;border-bottom: 1px solid;"
                                                v-for="(item, index) in searchList"
                                                @click="onSearchItemClick(index)"
                                                :style="getSearchStyle(index)">
                                                {{item.name}}
                                            </div>
                                        </div>
                                        <div style="height: 100%;padding: 0;font-size: 20px;
                                            border-left: 1px solid;"
                                            class="col-md-6">
                                            <div style="border-bottom: 1px solid;"
                                                v-for="(item, index) in choseList.values()">
                                                <div style="padding-left: 25px;
                                                    width: 80%;display: inline-block;">
                                                    {{item.name}}&nbsp;{{item.count>0?"数量："+item.count:null}}
                                                </div>
                                                <div style="width: 20%;display: inline-block;
                                                    cursor: pointer;" @click="onDeleteClick(item.id)">
                                                    删除
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div style="text-align: center; height: 60px; width: 100%;
                                background: rgb(226, 246, 248);"
                                ref="caseFooter">
                                <div class="row" style="height: 100%;margin: 0;">
                                    <div style="height: 100%;padding-top: 10px;padding-bottom: 10px;"
                                        class="col-md-3">
                                        <div style="height: 40px;line-height: 36px;font-size: 20px;
                                            background: rgb(253, 231, 176);border: 1px solid rgb(0, 0, 0);
                                            border-radius: 6px;vertical-align: center;cursor: pointer;"
                                            @click="onSubmitCase()">
                                            提交
                                        </div>
                                    </div>
                                    <div style="height: 100%;padding-top: 10px;padding-bottom: 10px;"
                                        class="col-md-3">
                                        <div style="height: 40px;line-height: 36px;font-size: 20px;
                                            background: rgb(253, 231, 176);border: 1px solid rgb(0, 0, 0);
                                            border-radius: 6px;vertical-align: center;cursor: pointer;"
                                            v-show="caseContentIndex===2||caseContentIndex===3"
                                            @click="onAddClick()">
                                            添加
                                        </div>
                                    </div>
                                    <div style="height: 100%;padding-top: 10px;padding-bottom: 10px;"
                                        class="col-md-3">
                                    </div>
                                    <div style="height: 100%;padding-top: 10px;padding-bottom: 10px;"
                                        class="col-md-3">
                                        <div style="height: 40px;line-height: 36px;font-size: 20px;
                                            background: rgb(253, 231, 176);border: 1px solid rgb(0, 0, 0);
                                            border-radius: 6px;vertical-align: center;cursor: pointer;"
                                            @click="onCaseInfoClick()">
                                            查看病历信息
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>`
}